package com.atguigu.daijia.rules.service.impl;

import com.atguigu.daijia.model.form.rules.FeeRuleRequest;
import com.atguigu.daijia.model.form.rules.FeeRuleRequestForm;
import com.atguigu.daijia.model.form.rules.FeeRuleResponse;
import com.atguigu.daijia.model.vo.rules.FeeRuleResponseVo;
import com.atguigu.daijia.rules.mapper.FeeRuleMapper;
import com.atguigu.daijia.rules.service.FeeRuleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {

    @Resource
    private KieContainer kieContainer;
    /**
     * 计算订单费用
     * 根据费用规则请求表单计算订单的费用规则响应
     * 此方法使用规则引擎（如Drools）来根据给定的距离、开始时间和等待分钟数来计算费用
     *
     * @param calculateOrderFeeForm 费用规则请求表单，包含距离、等待时间等信息
     * @return 返回计算出的订单费用规则响应对象FeeRuleResponseVo
     */
    @Override
    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm calculateOrderFeeForm) {
        // 创建费用规则请求对象，并设置距离和等待分钟数
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        feeRuleRequest.setDistance(calculateOrderFeeForm.getDistance());
        feeRuleRequest.setStartTime(new DateTime(feeRuleRequest.getStartTime()).toString("HH:mm:ss"));
        feeRuleRequest.setWaitMinute(calculateOrderFeeForm.getWaitMinute());

        // 新建规则引擎会话
        KieSession kieSession = kieContainer.newKieSession();
        // 创建费用规则响应对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        // 将费用规则响应对象设置到全局变量中，以便规则可以访问
        kieSession.setGlobal("feeRuleResponse",feeRuleResponse);
        // 将费用规则请求对象插入会话
        kieSession.insert(feeRuleRequest);
        // 触发所有规则的执行
        kieSession.fireAllRules();
        // 释放会话资源
        kieSession.dispose();

        // 创建费用规则响应VO对象，并将费用规则响应的数据复制到VO对象
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        BeanUtils.copyProperties(feeRuleResponse,feeRuleResponseVo);

        // 返回计算出的费用规则响应VO对象
        return feeRuleResponseVo;
    }
}
